﻿using IShoppingBll;
using IShoppingDal;
using ShoppingEntity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static ShoppingEntity.Returns;

namespace ShoppingBll
{
	/// <summary>
	/// 退货信息业务处理层
	/// </summary>
	public class ReturnsBll:BaseDeleteBll<Returns>, IReturnsBll
	{
		public IReturnsDal _returnsDal;
		public IUserInfoDal _userInfoDal;
		public ICommodityInfoDal _commodityInfoDal;
		public IDistributionInfoDal _distributionInfoDal;
		public IOrderInfoDal _orderInfoDal;
		public ShoppingDbContext _dbContext;
		
		public ReturnsBll(IReturnsDal returnsDal, 
			IUserInfoDal userInfoDal,
			ICommodityInfoDal commodityInfoDal,
			IDistributionInfoDal distributionInfoDal,
			IOrderInfoDal orderInfoDal,
			ShoppingDbContext dbContext) :base(returnsDal)
		{
			_returnsDal = returnsDal;
			_userInfoDal = userInfoDal;
			_commodityInfoDal = commodityInfoDal;
			_distributionInfoDal = distributionInfoDal;
			_orderInfoDal = orderInfoDal;
			_dbContext = dbContext;
		}


        /// <summary>
        /// 获取列表信息
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <param name="count"></param>
        /// <returns></returns>
        public object GetReturnsByPage(int page, int limit, out int count)
		{
			//获取数据库中配送全部的数据（未真实查询）
			var returns = _returnsDal.GetEntitiesDb().AsQueryable();
			
			//连表
			var tempDist = from r in returns

						   join c in _commodityInfoDal.GetEntitiesDb()
						   on r.GoodsId equals c.ID into rcTemp
						   from rc in rcTemp.DefaultIfEmpty()

						   join u in _userInfoDal.GetEntitiesDb().Where(u => !u.IsDelete)
						   on r.UserId equals u.ID into ruTemp
						   from ru in ruTemp.DefaultIfEmpty()

						   join u2 in _userInfoDal.GetEntitiesDb().Where(u => !u.IsDelete)
						   on r.UserId equals u2.ID into ru2Temp
						   from ru2 in ru2Temp.DefaultIfEmpty()

						   select new
						   {
							   r.ID,
							   r.OrderId,
							   rc.CommodityName,
							   ru.UserName,
							   r.Address,
							   DistributionName = ru2.UserName,
							   r.State,
							   r.SendTime,
							   r.CreateTime
						   };

			//查询出来数据的数量
			count = tempDist.Count();
			//分页
			tempDist = tempDist.Skip((page - 1) * limit).Take(limit);

			var list = tempDist.ToList().Select(r =>
			{
				string State = r.State.ToString();
				return new
				{
					r.ID,
					r.OrderId,
					r.CommodityName,
					r.UserName,
					r.Address,
					r.DistributionName,
					State,
					r.SendTime,
					r.CreateTime
				};
			});

			return list;
		}
		/// <summary>
		/// 获取状态下拉选
		/// </summary>
		/// <returns></returns>
		public object GetStatusSelectOption()
		{
			List<object> options = new List<object>();

			//获取枚举中所有的名字
			var names = Enum.GetNames(typeof(ReturnsStateEnum));

			foreach (var namesItem in names)
			{
				var value = (int)Enum.Parse(typeof(ReturnsStateEnum), namesItem);
				options.Add(new
				{
					Key = namesItem,
					Value = value
				});
			}
			return options;
		}


		/// <summary>
		/// 货物退回揽收
		/// </summary>
		/// <param name="returnsId"></param>
		/// <returns></returns>
		public bool CommBuyoff(string returnsId, string DistributionId)
		{
            using (var transaction= _dbContext.Database.BeginTransaction())
            {
				Returns returns = _returnsDal.GetEntity(returnsId);
				returns.State = ReturnsStateEnum.配送中;
				returns.DistributionId = DistributionId;
				bool isSuccess2 = _returnsDal.Update(returns);

				OrderInfo orderInfo = _orderInfoDal.GetEntity(returns.OrderId);
				orderInfo.State = OrderInfo.OrderStateEnum.货物运输中;
				bool isSuccess1 = _orderInfoDal.Update(orderInfo);

                if (isSuccess1 && isSuccess2)
                {
					transaction.Commit();
					return true;
                }
                else
                {
					transaction.Rollback();
					return false;
                }

			}
		}


		/// <summary>
		/// 确认送达
		/// </summary>
		/// <param name="returnsId"></param>
		/// <returns></returns>
        public bool BtnCommDelivery(string returnsId)
        {
			using (var transaction = _dbContext.Database.BeginTransaction())
			{
				Returns returns = _returnsDal.GetEntity(returnsId);
				returns.State = Returns.ReturnsStateEnum.已送达;
				returns.SendTime = DateTime.Now;
				bool isSuccess2 = _returnsDal.Update(returns);

				OrderInfo orderInfo = _orderInfoDal.GetEntity(returns.OrderId);
				orderInfo.State = OrderInfo.OrderStateEnum.已退回仓库;
				bool isSuccess1 = _orderInfoDal.Update(orderInfo);

				if (isSuccess1 && isSuccess2)
				{
					transaction.Commit();
					return true;
				}
				else
				{
					transaction.Rollback();
					return false;
				}
			}

		}
    }
}
